import {Injectable} from '@nestjs/common';
// ORM
import {InjectRepository} from '@nestjs/typeorm';
import {Repository, UpdateResult} from 'typeorm';
import {ApplyUserEntity} from '../entity/apply.user.entity';
import {ApplyUserDto} from '../dto/apply.user.dto';
import {ApplyUserAuthType, ApplyUserStatus} from "../common/constants";

@Injectable()
export class ApplyUserService {
    constructor(
        @InjectRepository(ApplyUserEntity)
        private readonly applyUserRepository: Repository<ApplyUserEntity>,
    ) {
    }

    async createOne(applyUserDto: ApplyUserDto): Promise<ApplyUserEntity> {
        return await this.applyUserRepository.save(applyUserDto);
    }

    async editOne(applyUserDto: ApplyUserDto): Promise<UpdateResult> {
        return await this.applyUserRepository.update({id: applyUserDto.id}, applyUserDto);
    }

    async delOne(id: string): Promise<UpdateResult> {
        return await this.applyUserRepository.update({id}, {status: ApplyUserStatus.DELETED});
    }

    async editAuthType(id: string, authType: ApplyUserAuthType): Promise<UpdateResult> {
        return await this.applyUserRepository.update({id}, {authType});
    }

    async getOneById(id: string): Promise<ApplyUserEntity> {
        const qb = this.applyUserRepository.createQueryBuilder();
        qb.where({id})
        return qb.getOne()
    }

    async getOneByAccountId(accountId: string): Promise<ApplyUserEntity> {
        const qb = this.applyUserRepository.createQueryBuilder();
        qb.where({accountId})
        return qb.getOne()
    }

    async getAll(status?: ApplyUserStatus): Promise<ApplyUserEntity[]> {
        const qb = this.applyUserRepository.createQueryBuilder();
        if (status) {
            qb.where({status})
        }
        return qb.getMany()
    }
}
